package edu.xidian.pnaWeb.web.contorller;

import edu.xidian.pnaWeb.web.common.Constant;
import edu.xidian.pnaWeb.web.model.AdminContext;
import edu.xidian.pnaWeb.web.model.Invocation;
import edu.xidian.pnaWeb.web.model.Response;
import edu.xidian.pnaWeb.web.service.AlgorithmServiceImpl;
import edu.xidian.pnaWeb.web.service.api.AlgorithmService;
import edu.xidian.pnaWeb.web.service.api.PetriDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * @Description
 * @Author He
 * @Date 2021/10/3 17:22
 */
@RestController
@Slf4j
public class ApiController {
	@Resource
	private PetriDataService petriDataService;
	@Resource
	private AlgorithmService algorithmService;

	@PostMapping("/getResult")
	public Response algorithmApi(@RequestBody String dataJson, HttpSession session)  {
		try {
			Invocation invocation = petriDataService.transformData(dataJson,session);
			Method declaredMethod = AlgorithmServiceImpl.class.getDeclaredMethod(invocation.getMethodName(), Map.class);
			Object invoke = declaredMethod.invoke(algorithmService, invocation.getParams());
			return Response.success(invoke.toString());
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.toString());
			return Response.error(e.getMessage());
		}finally {
			session.setAttribute("adminContext",AdminContext.USER_INFO.get());
			AdminContext.USER_INFO.remove();
		}
	}
}
